package com.iqiyi.pps.epg.api.server.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.net.HttpHeaders;
import com.iqiyi.pps.epg.api.server.iservice.ProgramDirectorApiService;
import com.iqiyi.pps.epg.api.server.proxy.ProgramDirectorProxy;
import com.iqiyi.pps.epg.api.utils.*;
import org.apache.http.cookie.Cookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.ws.rs.core.MultivaluedMap;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by karkarrotxu on 2017/3/2.
 */
@Service("programDirectorApiServiceImpl")
public class ProgramDirectorApiServiceImpl extends ApiServiceImpl implements ProgramDirectorApiService {
    private static Logger logger = LoggerFactory.getLogger(ProgramDirectorApiServiceImpl.class);

    @Autowired
    private ProgramDirectorProxy proxy;

    private JSONArray jsonObj;

    @Override
    public String testMsg() {
        //   System.err.println("remoteIpPort=" + httpHeaders.getRequestHeader("Remote-Ip-Port"));
        //     logger.error("[test masg]",new Exception("测试用") );
        return Constants.getJsonResponse(Constants.CODE_SUC, null, "test");
    }

    @Override
    public String start(String directorId) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.startDirector(directorId);
    }

    @Override
    public String stop(String directorId) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.stopDirector(directorId);
    }

    @Override
    public String edit(String entity) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.editDirector(entity);
    }

    @Override
    public String addDirector(String entity) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.addDirector(entity);
    }

    @Override
    public String enableBackup() {
        return null;
    }

    @Override
    public String resourceAdd(String directorId,
                              String programQipuId,
                              String signalLegoId,
                              String signalType,
                              String signalId,
                              String isBackup,
                              String isDefaultBackup,
                              String signalName,
                              String signalUrl,
                              String signalPreviewUrl) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.resourceAdd(directorId, programQipuId, signalLegoId, signalType, signalId, isBackup,isDefaultBackup, signalName, signalUrl,signalPreviewUrl);
    }

    @Override
    public String resourceEdit(String id, String isDefaultBackup, String signalName, String playStatus,String directorId) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.resourceEdit(id,isDefaultBackup,signalName,playStatus,directorId);
    }

    @Override
    public String resourceDel(String id,String directorId) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.resourceDel(id,directorId);
    }

    @Override
    public String resourceNotice() {
        return null;
    }

    @Override
    public String resourceGetList(String directorId, String isBackup) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.resourceGetList(directorId, isBackup);
    }

    @Override
    public String resourceSwitch(String id, String directorId,String time, String playCounts) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.resourceSwitch(id, directorId,time,playCounts);
    }

    @Override
    public String listDirector(String qipuId, String pname, String startDate, String endDate,
                               String programStatus, String playStatus, Integer pageNo, Integer pageSize, String fullMode) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.listDirector(qipuId, pname, startDate, endDate,
                programStatus, playStatus, pageNo, pageSize,fullMode);
    }

    @Override
    public String getLogList(String directorId,Integer pageNo, Integer pageSize){
        CrossDataLocalPool.set(getCrossData());
        return proxy.getLogList(directorId,pageNo,pageSize);
    }

    @Override
    public String switchBackUp(String directorId){
        CrossDataLocalPool.set(getCrossData());
        return proxy.switchBackUp(directorId);
    }

    @Override
    public String delDirector(String directorId){
        CrossDataLocalPool.set(getCrossData());
        return proxy.delDirector(directorId);
    }

    @Override
    public String releaseDirector(String directorId) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.releaseDirector(directorId);
    }

    @Override
    public String effectAdd(String data) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.effectAdd(data);
    }

    @Override
    public String effectEdit(int id, String url, String name, String location, String extraInfo, String status,
                             String directorId, int isPreview) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.effectEdit(id, url, name, location, extraInfo, status, directorId, isPreview);
    }

    @Override
    public String effectDelete(int id, String directorId) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.effectDelete(id, directorId);
    }

    @Override
    public String effectList(String directorId, int type, String status) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.effectList(directorId, type, status);
    }

    @Override
    public String redirectRequest(String requestJson) {
        JSONObject entity = JSONObject.parseObject(requestJson);
        String url = entity.getString("url");
        JSONObject params = entity.getJSONObject("params");
        JSONObject headers = entity.getJSONObject("headers");
        String type = entity.getString("type");
        String result = null;
        Map<String, Object> headersMap = quickToMap(headers);

        if (entity.containsKey("needCookie")) {
            MultivaluedMap<String, String> vars = httpHeaders.getRequestHeaders();
            Map<String, Cookie> map = new HashMap<String, Cookie>();
            String cookieValue = SsoUtil.getLegoLoginCookie(httpHeaders);
            logger.info("loginCookie" + cookieValue);
            if (cookieValue != null) {
                headersMap.put(HttpHeaders.COOKIE, SsoUtil.LEGO_USERID_COOKIE_KEY + "=" + cookieValue);
            }
        }

        if ("get".equalsIgnoreCase(type)) {
            result = ApiHttpRequestUtil.getMethod(url, headersMap, quickToMap(params));
        } else if ("post".equalsIgnoreCase(type)) {
            if(entity.containsKey("raw")) {
                JSONObject jsonResult = ApiHttpRequestUtil.doPostRaw(url, entity.getString("params"));

                if(null == jsonResult) {
                    result = "response null";
                }else{
                    result = jsonResult.toJSONString();
                }

            }else {
                result = ApiHttpRequestUtil.postMethod(url, headersMap, quickToMap(params));
            }
        }

        if (entity.containsKey("logType") && entity.containsKey("directorId")) {
            ServiceUtil.writeDirectorLog(entity.getIntValue("directorId"), entity.getIntValue("logType"), null,
                    result + " | " + requestJson);
        }

        return result;
    }

    @Override
    public String commentaryAdd(String name, String programQipuId, String directorId, String streamUrl) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.commentaryAdd(name, programQipuId, directorId, streamUrl);
    }

    @Override
    public String commentaryEdit(String name, int id, String programQipuId, String directorId, String streamUrl,
                                 String volumn, String status) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.commentaryEdit(name, id, programQipuId, directorId, streamUrl, volumn, status);
    }

    @Override
    public String commentaryList(String directorId, String programQipuId, int id) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.commentaryList(directorId, programQipuId, id);
    }

    @Override
    public String commentaryDel(int id, String directorId) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.commentaryDel(id, directorId);

    }

    @Override
    public String setMainResource(String pid, String mainResourceId) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.setMainResource(pid, mainResourceId);
    }

    @Override
    public String setResourcePlayCounts(String id, Integer playCounts) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.setResourcePlayCounts(id, playCounts);
    }

    @Override
    public String setDirectorResourceId(long programQipuId, int playResouceId, int downResourceId) {
        CrossDataLocalPool.set(getCrossData());
        return proxy.setDirectorResourceId(programQipuId, playResouceId, downResourceId);
    }
}
